package sample.jsp.configuration;

import org.apache.log4j.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import java.nio.charset.Charset;
import java.util.List;

@Configuration  
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter{
	
	private Logger log = Logger.getLogger(WebConfig.class);
	
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();//将静态资源的请求转发到servlet容器中默认的servlet上
    }
    
    @Bean
    public ViewResolver jspViewResolver() {
        InternalResourceViewResolver resolver= new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/jsp");
        resolver.setSuffix(".jsp");
        resolver.setViewClass(org.springframework.web.servlet.view.JstlView.class);
        return resolver;
    }  
    
    @Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {  
    	log.info("addResourceHandlers");  
        registry.addResourceHandler("/static/**").addResourceLocations("/static/");  
    }  
    
    @Override
	public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    	StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();
    	stringHttpMessageConverter.setDefaultCharset(Charset.forName("UTF-8"));
    	
    	MappingJackson2HttpMessageConverter mappingJackson2HttpMsgConverter = new MappingJackson2HttpMessageConverter();
    	mappingJackson2HttpMsgConverter.setDefaultCharset(Charset.forName("UTF-8"));
    	//mappingJackson2HttpMsgConverter.setObjectMapper(objectMapper);
    	
    	converters.add(mappingJackson2HttpMsgConverter);
    	converters.add(stringHttpMessageConverter);
	}
    

}
